package com.kakarote.ids.provider.utils;

import com.alibaba.fastjson.util.TypeUtils;
import com.alicp.jetcache.Cache;
import com.alicp.jetcache.CacheLoader;
import com.kakarote.common.entity.SimpleUser;
import com.kakarote.common.entity.UserInfo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

public class UserCacheUtil {
    static Cache<Long, UserInfo> userCache;

    static Cache<Long, String> deptCache;

    public static CacheLoader<Long, UserInfo> userInfoCacheLoader;

    public static CacheLoader<Long, String> deptCacheLoader;

    public static <T> List<String> getUserNameList(List<T> userIds) {
        if (userIds == null || userIds.isEmpty())
            return Collections.emptyList();
        List<String> stringList = new ArrayList<>(userIds.size());
        for (T obj : userIds) {
            String name = getUserName(TypeUtils.castToLong(obj));
            if (!"".equals(name))
                stringList.add(name);
        }
        return stringList;
    }

    public static String getUserName(Long userId) {
        if (userId == null)
            return "";
        return getUserInfo(userId).getUsername();
    }

    public static String getDeptName(Long deptId) {
        if (deptId == null)
            return "";
        return (String) deptCache.computeIfAbsent(deptId, (Function) deptCacheLoader);
    }

    public static UserInfo getUserInfo(Long userId) {
        if (Objects.isNull(userId))
            return new UserInfo();
        return (UserInfo) userCache.computeIfAbsent(userId, (Function) userInfoCacheLoader);
    }

    public static SimpleUser getSimpleUser(Long userId) {
        UserInfo userInfo = getUserInfo(userId);
        SimpleUser simpleUser = new SimpleUser();
        simpleUser.setUserId(userInfo.getUserId());
        simpleUser.setUserImg(userInfo.getUserImg());
        simpleUser.setUsername(userInfo.getUsername());
        simpleUser.setEmail(userInfo.getEmail());
        simpleUser.setMobile(userInfo.getMobile());
        if (userInfo.getUserStatus() != null)
            simpleUser.setStatus(userInfo.getUserStatus().getValue());
        simpleUser.setNickname(userInfo.getNickname());
        return simpleUser;
    }

    public static List<SimpleUser> getSimpleUsers(List<Long> userIds) {
        if (userIds == null || userIds.isEmpty())
            return Collections.emptyList();
        return (List<SimpleUser>) userIds.stream().map(UserCacheUtil::getSimpleUser).collect(Collectors.toList());
    }
}
